package com.hk.userservice.controller;

import com.github.pagehelper.PageInfo;
import com.hk.commons.CommonResult;
import com.hk.model.Admin;
import com.hk.model.LoginLog;
import com.hk.model.vo.LoginAdmin;
import com.hk.model.vo.Result;
import com.hk.model.vo.ResultVO;
import com.hk.userservice.service.AdminService;
import com.hk.userservice.service.LoginLogService;
import com.hk.userservice.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;


/**
 * @Author: aerfazhe
 * @Date: 2021/7/1 11:09
 * @Statement:
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Value("${jwt.tokenHead}")
    String tokenHead;

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private LoginLogService loginLogService;

    @PostMapping("/tologin")
    public CommonResult tologin(@RequestBody LoginAdmin loginAdmin, HttpServletRequest request) {
        HashMap<String, String> data = new HashMap<>();
        String token = null;
        try {
            token = adminService.toLogin(loginAdmin, request);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("用户名或密码错误");
        }
        if (StringUtils.isEmpty(token)) {
            return CommonResult.failed("用户名或密码错误");
        }
        data.put("tokenHead", tokenHead);
        data.put("access_token", token);
        return CommonResult.success(data);
    }

    @ApiOperation("获取当前管理员登录信息")
    @GetMapping("/loginAdmin")
    public Result loginAdmin(HttpServletRequest request) {
//        获取token
        String header = request.getHeader("Authorization");
        if (header != null) {
            String token = header.substring(7);
//        获取负载
            Claims claims = jwtTokenUtil.getClaimsFromToken(token);
            Integer id = (Integer) claims.get("id");
            Integer loginLogId = (Integer) claims.get("loginLogId");
            String name = (String) claims.get("name");
            LoginAdmin loginAdmin = LoginAdmin.builder().id(id)
                    .name(name).loginLogId(loginLogId).build();
            Result result = CommonResult.successResult(loginAdmin);
            return result;
        }
        Result result = CommonResult.acResult("暂未登录或token已经过期");
        return result;
    }

    //     通过登录用户Id不查询自身，查询其余所有管理员
    @GetMapping("/pageList")
    public ResultVO<Admin> findAll(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            Admin admin,
            HttpServletRequest request
    ) {
//        从token中获取登录用户Id
        String header = request.getHeader("Authorization");
        if (header != null) {
            String token = header.substring(7);
//        获取负载
            Claims claims = jwtTokenUtil.getClaimsFromToken(token);
//        获取id
            Integer id = (Integer) claims.get("id");
            admin.setId(id);
        }
        List<Admin> adminList = adminService.findAll(page, limit, admin);
        PageInfo<Admin> adminPageInfo = new PageInfo<>(adminList);
        int count = adminService.count(-1, -1, admin);
        if (adminList.isEmpty()) {
            ResultVO resultVO = CommonResult.nullResultVO(count, adminPageInfo.getList());
            return resultVO;
        }
        ResultVO resultVO = CommonResult.successResultVO(count, adminPageInfo.getList());
        return resultVO;
//        return null;
    }

    @ApiOperation("通过Id查询管理员详情")
    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable int id) {
        Admin admin = adminService.findById(id);
        if (admin.getId() == 0) {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        Result result = CommonResult.successResult(admin);
        return result;

    }

    /**
     * 邮箱校验
     *
     * @param email 原始邮箱
     * @return
     */
    @GetMapping("/findByEmail")
    public Result findByEmail(@RequestParam(required = false) String email) {
        if (email == null || email == "") {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        int email1 = adminService.findByEmail(email);
        if (email1 == 1) {
            Result result = CommonResult.successResult(null);
            return result;
        }
        Result result = CommonResult.nullResult(null);
        return result;
//        return null;
    }

    //    添加管理员
    @ApiOperation("添加管理员")
    @PostMapping("/save")
    public Result save(@RequestBody(required = false) Admin admin) {
        if (admin == null) {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        adminService.save(admin);
        Result result = CommonResult.successResult(null);
        return result;
    }

    @ApiOperation("修改当前登录管理员的信息")
    @PostMapping("/updateMessage")
    public Result updateMessage(@RequestBody Admin admin) throws IOException {
        adminService.update(admin);
        Result result = CommonResult.successResult(null);
        return result;
    }

    @ApiOperation("修改管理员的信息")
    @PostMapping("/currentUpdateMessage")
    public Result currentUpdateMessage(@RequestBody Admin admin) throws IOException {
        adminService.update(admin);
        Result result = CommonResult.successResult(null);
        return result;
    }

    @ApiOperation("修改当前登录管理员密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody Admin admin) {
        adminService.updatePassWord(admin);
        Result result = CommonResult.successResult(null);
        return result;
    }

    //    todo 删除管理员(已完毕)
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) throws IOException {
        int delete = adminService.delete(id);
        if (delete == 1) {
            Result result = CommonResult.successResult(null);
            return result;
        }
        Result result = CommonResult.nullResult(null);
        return result;
    }

    /**
     * 退出登录
     *
     * @param loginLogId 当前登录账户日志ID
     * @param session
     * @return
     */
    @GetMapping("/destroyLogin")
    public Result destroyLogin(Integer loginLogId, HttpSession session) throws IOException {
//        Session删除登录信息
//        session.removeAttribute("admin");
//        Redis删除登录信息
       /* Long del = jedis.del("admin");
        if (del < 1) {
            Result result = CommonResult.errorResult(null);
            return result;
        }*/
//   保存当前登录账户退出时间 和状态 0：使用中 1：已下线
        LoginLog loginLog = LoginLog.builder()
                .id(loginLogId)
                .state(1).build();
        int update = loginLogService.update(loginLog);
        if (update == 1) {
            log.error("退出登录");
            Result result = CommonResult.successResult("退出登录！");
            return result;
        }
        log.error("未登录");
        Result result = CommonResult.errorResult("参数或系统异常，请稍后重试！");
        return result;

    }

    /**
     * 匹配当前用户是否具有该权限
     * @param uri 请求路径
     * @param id 当前登录用户Id
     * @return
     */
    @GetMapping("/permission-to-check")
    public Result permissionToCheck(String uri,Integer id) {
        boolean isExist = adminService.permissionToCheck(uri,id);
        if (isExist) {
            Result result = CommonResult.successResult("拥有此权限");
            return result;
        }
        Result result = CommonResult.forbiddenResult("权限不足!");
        return result;
    }


}
